package com.awenhui.demo.quickstart;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author yuxf
 * @version 1.0
 * @date 2021/5/31 9:26
 */
public class ReflectTest {

    public static void main(String[] args) throws InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException, NoSuchFieldException {
        test01();
    }

    public static void test01() throws IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException {

        Class clazz = Student.class;
        //调用无参构造函数创建对象
        Student s1 = (Student) clazz.newInstance();

        //获取构造器，根据指定构造器创建对象
        Constructor constructor = clazz.getConstructor(String.class, int.class);
        Student s2 = (Student) constructor.newInstance("于大方", 18);

        //获取方法并执行
        Method getName = clazz.getMethod("getName");
        String s1Name = (String)getName.invoke(s1);

        Method setName = clazz.getMethod("setName", String.class);
        setName.invoke(s1,"小花");

        //get获取和set设置属性的值
        Field nameFiled = clazz.getDeclaredField("name");
        //如果是私有属性要设置Accessible为true
        nameFiled.setAccessible(true);
        String name = (String)nameFiled.get(s1);
        System.out.println(name);
        nameFiled.set(s1,"小山");
        System.out.println(s1.getName());





    }
}

class ApiResult<T>
{
    private int code;
    private String message;
    private T data;

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }
}

class Student {

    public Student() {
        this.name = "小明";
        this.age = 3;
    }

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    private String name;
    private int age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
